<template>
  <div class="app-container">
    <!--顶部搜索-->
    <div class="search-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item prop="userName">
          <el-input
            v-model="queryParams.userName"
            placeholder="请输入账号"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="phonenumber">
          <el-input
            v-model="queryParams.phonenumber"
            placeholder="请输入手机号码"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="用户状态"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <div class="btn-container">
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button
              icon="el-icon-download"
              size="mini"
              @click="handleImport"
              v-hasPermi="['system:user:import']"
              >导入
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:user:add']"
              >新增
            </el-button>
          </el-col>
        </el-row>
      </div>
    </div>

    <!--列表-->
    <el-table
      v-loading="loading"
      :data="userList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column
        label="账号"
        align="center"
        key="userName"
        prop="userName"
        v-if="columns[0].visible"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="姓名"
        align="center"
        key="nickName"
        prop="nickName"
        v-if="columns[1].visible"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="手机号码"
        align="center"
        key="phonenumber"
        prop="phonenumber"
        v-if="columns[2].visible"
        width="120"
      />
      <el-table-column
        label="角色"
        align="center"
        key="roles"
        prop="roles"
        v-if="columns[3].visible"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope" v-if="scope.row.roles.length">
          <div v-for="(item, i) in scope.row.roles">{{ item.roleName }}</div>
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        align="center"
        key="status"
        v-if="columns[4].visible"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        v-if="columns[5].visible"
        width="160"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="200"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope" v-if="scope.row.userId !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-key"
            @click="handleRegister(scope.row)"
            >注册key</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:user:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:user:remove']"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-tickets"
            @click="handleResetPwd(scope.row)"
            v-hasPermi="['system:user:resetPwd']"
            >重置密码</el-button
          >
          <!--<el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['system:user:resetPwd', 'system:user:edit']">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleResetPwd" icon="el-icon-key"
                                v-hasPermi="['system:user:resetPwd']">重置密码</el-dropdown-item>
              <el-dropdown-item command="handleAuthRole" icon="el-icon-circle-check"
                                v-hasPermi="['system:user:edit']">分配角色</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>-->
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- 编辑有的字段不显示但还占空间，前两行干脆写两套 -->
        <!-- 新增时 -->
        <div v-if="form.userId == undefined">
          <el-row>
            <el-col :span="12">
              <el-form-item label="账号" prop="userName">
                <el-input
                  v-model="form.userName"
                  placeholder="请输入账号"
                  maxlength="30"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="姓名" prop="nickName">
                <el-input
                  v-model="form.nickName"
                  placeholder="请输入姓名"
                  maxlength="30"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item
                v-if="form.userId == undefined"
                label="用户密码"
                prop="password"
              >
                <el-input
                  v-model="form.password"
                  placeholder="请输入用户密码"
                  type="password"
                  maxlength="20"
                  show-password
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态">
                <el-radio-group v-model="form.status">
                  <el-radio
                    v-for="dict in dict.type.sys_normal_disable"
                    :key="dict.value"
                    :label="dict.value"
                    >{{ dict.label }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <!-- 编辑时 -->
        <div v-else>
          <el-row>
            <el-col :span="12">
              <el-form-item label="姓名" prop="nickName">
                <el-input
                  v-model="form.nickName"
                  placeholder="请输入姓名"
                  maxlength="30"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态">
                <el-radio-group v-model="form.status">
                  <el-radio
                    v-for="dict in dict.type.sys_normal_disable"
                    :key="dict.value"
                    :label="dict.value"
                    >{{ dict.label }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input
                v-model="form.phonenumber"
                placeholder="请输入手机号码"
                maxlength="11"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="form.email"
                placeholder="请输入邮箱"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属部门" prop="deptId">
              <treeselect
                v-model="form.deptId"
                :options="deptList"
                placeholder="请选择部门"
              />
              <!--            <el-select v-model="form.deptId" placeholder="请选择部门">-->
              <!--              <el-option v-for="dict in deptList" :key="dict.deptId" :label="dict.deptName"-->
              <!--                         :value="dict.deptId"></el-option>-->
              <!--            </el-select>-->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="roleIds">
              <el-select
                v-model="form.roleIds"
                multiple
                placeholder="请选择角色"
              >
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="用户性别">
              <el-select v-model="form.sex" placeholder="请选择性别">
                <el-option
                  v-for="dict in dict.type.sys_user_sex"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  resetUserPwd,
  changeUserStatus,
  deptTreeSelect,
} from "@/api/system/user";
import { listDept } from "@/api/system/dept";
import { getToken } from "@/utils/auth";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import { register, registerVerify, loginUkeyVerify } from "@/api/system/user";
import webauthn from "@/assets/js/webauthn";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Account",
  dicts: ["sys_normal_disable", "sys_user_sex"],
  components: { Treeselect },
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
      },
      userList: [],
      total: 0,
      loading: false,
      // 列信息
      columns: [
        { key: 0, label: `账号`, visible: true },
        { key: 1, label: `姓名`, visible: true },
        { key: 2, label: `手机号码`, visible: true },
        { key: 3, label: `角色`, visible: true },
        { key: 4, label: `状态`, visible: true },
        { key: 5, label: `创建时间`, visible: true },
      ],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData",
      },
      // 表单参数
      form: {},
      rules: {
        roleIds: [
          { required: true, message: "用户角色不能为空", trigger: "blur" },
        ],
        userName: [
          { required: true, message: "账号不能为空", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "账号长度必须介于 2 和 20 之间",
            trigger: "blur",
          },
        ],
        nickName: [
          { required: true, message: "姓名不能为空", trigger: "blur" },
        ],
        deptId: [
          { required: true, message: "部门不能为空", trigger: "submit" },
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          {
            min: 5,
            max: 20,
            message: "用户密码长度必须介于 5 和 20 之间",
            trigger: "blur",
          },
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        phonenumber: [
          {
            required: true,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
      initPassword: "123456",
      title: "",
      open: false,
      deptList: [],
    };
  },

  created() {
    this.getList();
    this.getDeptList();
  },
  methods: {
    //查询用户列表
    getList() {
      this.loading = true;
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },

    getDeptList() {
      deptTreeSelect({}).then((res) => {
        if (res.code === 200) {
          this.deptList = res.data;
        }
      });
    },
    //表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        postIds: [],
        roleIds: [],
      };
      this.resetForm("form");
    },

    //导入
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },

    importTemplate() {
      this.download(
        "system/user/importTemplate",
        {},
        `user_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    //新增
    handleAdd() {
      this.reset();
      console.log(this.form.password);
      getUser().then((response) => {
        this.postOptions = response.posts;
        this.roleOptions = response.roles;
        this.open = true;
        this.title = "添加用户";
        this.form.password = this.initPassword;
      });
    },

    //注册key
    handleRegister(row) {
      console.log(row.userName);
      this.beginRegister(row.userName);
    },

    //注册主体方法
    beginRegister(name) {
      // this.userName = "admin";
      let data = {
        userName: name,
      };
      let options = undefined;

      if (data.userName) {
        register(data.userName)
          .then((res) => {
            if (res.code === 200) {
              options = res.data.data;
              let challenge = options.challenge.value;
              let user_name = options.user.name;
              let user_key = res.data.userKey;
              console.log(111);

              // let options = {
              //   "rp": {
              //   "id": "localhost",
              //   "name": "localhost"
              //   },
              //   "user": {
              //   "id": "dXNlcl9pZA==",
              //   "name": "john_doe",
              //   "displayName": "john_doe"
              //   },
              //   "pubKeyCredParams": [
              //   { "type": "public-key", "alg": -7 },
              //   { "type": "public-key", "alg": -257 }
              //   ],
              //   "authenticatorSelection": {
              //   "authenticatorAttachment": "cross-platform",
              //   "userVerification": "preferred"
              //   },
              //   "challenge": "7a1cNQKtx3YN5JVemYIh5w==",
              //   "allowCredentials": [{
              //   "id": "YWxsb3dfY3JlZGVudGlhbA==",
              //   "type": "public-key"
              // }]
              // };

              this.authCreatePublicKeyLocal(options).then((credential) => {
                if (credential) {
                  this.authRegisterVerifyServer(
                    challenge,
                    user_name,
                    user_key,
                    credential
                  )
                    .then((response) => {
                      console.log("OK");
                    })
                    .catch((err) => {
                      console.log(err);
                    });
                } else {
                  console.log("获取本地认证失败");
                  // this.loading = false;}
                }
              });
            } else {
              this.$message.error(res.errorMsg);
            }
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        this.$message.warning("请输入账号!");
      }
    },

    async authCreatePublicKeyLocal(options) {
      const publicKeyCredentialCreateOptions =
        webauthn.transformCredentialCreateOptions(options);

      let credential;
      try {
        credential = await navigator.credentials.create({
          publicKey: publicKeyCredentialCreateOptions,
        });
        console.log("本地电子Key:" + JSON.stringify(credential));
      } catch (err) {
        console.log(err);
        this.$message.warning("获取本地认证失败");
      }
      return credential;
    },

    async authRegisterVerifyServer(challenge, user_name, user_key, credential) {
      const transformedAssertionForServer =
        webauthn.transformNewAssertionForServer(credential);

      //  console.log(JSON.stringify(credential));
      transformedAssertionForServer["challenge"] = challenge;
      transformedAssertionForServer["userKey"] = user_key;
      transformedAssertionForServer["userName"] = user_name;

      // console.log("transformedAssertionForServer:"+JSON.stringify(transformedAssertionForServer))

      try {
        registerVerify(transformedAssertionForServer).then((res) => {
          if (res.code === 200) {
            this.$message.success("认证成功");
          } else {
            this.$message.warning("认证失败");
          }
        });
      } catch (err) {
        this.$message.warning("认证失败");
      }
      return response;
    },

    //修改
    handleUpdate(row) {
      this.reset();
      const userId = row.userId || this.ids;
      getUser(userId).then((response) => {
        this.form = response.data;
        this.roleOptions = response.roles;
        this.$set(this.form, "roleIds", response.roleIds);
        this.open = true;
        this.title = "修改用户";
        this.form.password = "";
      });
    },

    //删除
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$modal
        .confirm('是否确认删除用户编号为"' + userIds + '"的数据项？')
        .then(function () {
          return delUser(userIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    //取消
    cancel() {
      this.open = false;
      this.reset();
    },

    //提交
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.userId != undefined) {
            updateUser(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    //查询
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    //重置
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    //全选
    handleSelectionChange() {},

    //修改用户状态
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal
        .confirm('确认要"' + text + '""' + row.userName + '"用户吗？')
        .then(function () {
          return changeUserStatus(row.userId, row.status);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },

    //重置密码按钮操作
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
      })
        .then(({ value }) => {
          resetUserPwd(row.userId, value).then((response) => {
            this.$modal.msgSuccess("修改成功，新密码是：" + value);
          });
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
.search-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 21px;

  .btn-container {
    display: flex;
    align-items: center;
  }
}

.el-form--inline ::v-deep .el-form-item {
  margin-bottom: 0 !important;
}

/*::v-deep .el-form-item {*/
/*  margin-bottom: 0 !important;*/
/*}*/
</style>
